package com.antler.smt.admin.service.impl;

import com.antler.smt.admin.mapper.OrderEntityMapper;
import com.antler.smt.admin.mapper.PurchaserAccountInfoMapper;
import com.antler.smt.admin.mapper.PurchaserEntityMapper;
import com.antler.smt.constant.DateTimeConstant;
import com.antler.smt.constant.OrderConstant;
import com.antler.smt.entity.OrderEntity;
import com.antler.smt.entity.PurchaserAccountEntity;
import com.antler.smt.entity.PurchaserEntity;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.request.admin.JoinSupplierReq;
import com.antler.smt.request.admin.PurchserAccountReq;
import com.antler.smt.response.base.Result;
import com.antler.smt.service.admin.OrderService;
import com.antler.smt.utils.DateUtil;
import com.antler.smt.utils.LogUtil;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单接口
 *
 * @author zhangyi
 * @date 2018/3/29 17:36
 */
@Service
public class OrderServiceImpl implements OrderService {

    /**
     * 日志
     */
    private static Logger log = LogUtil.get();

    @Autowired
    private OrderEntityMapper orderEntityMapper;

    @Autowired
    private PurchaserAccountInfoMapper purchaserAccountInfoMapper;

    @Autowired
    private PurchaserEntityMapper purchaserEntityMapper;

    /**
     * 对接其服务商
     *
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> updateOrderSupplierId(JoinSupplierReq req) {
        Result result = null;

        //订单实体
        OrderEntity orderEntity = new OrderEntity();

        //更新服务商id
        orderEntity.setSupplierId(req.getSupplierId());

        //添加主键
        orderEntity.setId(req.getOrderId());

        //进度 0商务专员待采购商付款 1待确认付款 2待对接服务商 3待生产完成  4待收货 6待评价 7待付款给服务商 8结束 100驳回 200退款申请 201退款审核通过 202退款审核驳回
        orderEntity.setStatus(OrderConstant.ORDER_WAIT_PRODUCE_END);

        orderEntity.setPriceToSupplier(req.getPriceToSupplier());
        int i = orderEntityMapper.updateByPrimaryKeySelective(orderEntity);

        boolean flag = (0 == i);
        if (flag) {
            result = new Result(ResultCodeEnum.MODIFY_DATA_ERROR);
        }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }
        return result;
    }

    /**
     *  项目专员审核支付金额 ,确认付款
     *
     * @param orderId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> auditPayment(Long orderId,Integer payAuditType,Long payAuditAmmont,Long purchaserId) {
        Result result = null;

        //创建订单实体
        OrderEntity orderEntity = new OrderEntity();

        //主键id
        orderEntity.setId(orderId);

        //进度 0商务专员待采购商付款 1待确认付款 2待对接服务商 3待生产完成  4待收货 6待评价 7待付款给服务商 8结束 100驳回 200退款申请 201退款审核通过 202退款审核驳回
        orderEntity.setStatus(OrderConstant.ORDER_WAIT_JOIN_SUPPLIER);

        //审核支付类型
        orderEntity.setPayAuditType(Byte.parseByte(String.valueOf(payAuditType)));

        //审核支付金额
        orderEntity.setPayAuditAmmont(payAuditAmmont);

        //支付审核时间
        orderEntity.setPayAuditTime(DateUtil.stampToDate(System.currentTimeMillis()));

        //更新时间
        orderEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        int i = orderEntityMapper.updateByPrimaryKeySelective(orderEntity);

        if(0 == i){
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        }else{
            //判断支付类型 只用余额支付才减去
            if(payAuditType.equals(OrderConstant.BALANCE)) {

                //获取当前采购商
                PurchaserEntity purchaserEntity = purchaserEntityMapper.selectByPrimaryKey(purchaserId);

                //审核通过后，将采购商余额的钱减去
                PurchserAccountReq purchserAccountReq = new PurchserAccountReq();
                Long memberId = purchaserEntity.getMemberId();

                purchserAccountReq.setMemberId(memberId);

                //获取采购商账户信息
                PurchaserAccountEntity purchaserAccountEntity =
                        purchaserAccountInfoMapper.selectPurchaserAccountByMemberId(memberId);

                //获取采购商当前余额
                Long moneyLeft = purchaserAccountEntity.getMoneyLeft();
                Long nowMoneyLeft = moneyLeft - payAuditAmmont;
                if(0 < nowMoneyLeft){
                    purchserAccountReq.setMoneyLeft(nowMoneyLeft);
                    int i1 = purchaserAccountInfoMapper.updatPurchaserAccount(purchserAccountReq);
                    if(i1 == 0){
                        result = new Result(ResultCodeEnum.MODIFY_DATA_ERROR);
                    }else{
                        result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
                    }
                }else{
                    log.error("该采购商的余额不足，无法操作！",new RuntimeException("该采购商余额不足！"));
                }
            }else{
                result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
            }
        }
        return result;
    }

    /**
     * 项目专员付款给服务商
     *
     * @param orderId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> paymentSupplier(Long orderId) {
        Result result = null;

        //创建订单实体
        OrderEntity orderEntity = new OrderEntity();

        //设置订单id
        orderEntity.setId(orderId);

        //设置订单状态 8
        orderEntity.setStatus(OrderConstant.ORDER_END);

        //设置更新时间
        orderEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        int i = orderEntityMapper.updateByPrimaryKeySelective(orderEntity);

        if(0 == i){
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }

        return result;
    }

    /**
     * 商务专员填写对采购商的价格
     *
     * @param orderId
     * @param price
     * @return
     */
    @Override
    public Result updatePurchaserPrice(Long orderId, Long price) {
        Result result = null;
        //订单实体
        OrderEntity orderEntity = new OrderEntity();

        orderEntity.setId(orderId);
        orderEntity.setPriceToPurchaser(price);
        orderEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        int i = orderEntityMapper.updateByPrimaryKeySelective(orderEntity);
        result = (0 == i)?new Result(ResultCodeEnum.APPEND_DATA_ERROR):new Result(ResultCodeEnum.OPERATION_SUCCESS);

        return result;
    }
}
